<?php

namespace app\admin\controller\user;

use app\common\controller\Backend;
use app\common\library\Auth;
use think\Config;
use think\Db;
use think\Exception;
use think\exception\HttpResponseException;
use think\Session;
use fast\Random;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;



/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname';

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;
    protected $grouplist = [];

    protected $cur_shop = null;
    protected $admin_shop = null;
    //用户分组
    protected $user_group_model = null;
    //店铺模型
    protected $shop_model = null;
    //职员模型
    protected $staff_model = null;
    //服务商模型
    protected $service_model = null;
    protected $order_goods_model = null;
    //卡项模型
    protected $order_item_model = null;
    protected $order_item_info_model = null;

    protected $order_model = null;
    //优惠券领取模型
    protected $coupon_receive_model = null;
    //标签模型
    protected $tag_model = null;
    //标签用户关系模型
    protected $tag_user_model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\User;
        $this->user_group_model = new \app\admin\model\UserGroup;
        $this->shop_model = new \app\admin\model\store\Shop;
        $this->staff_model = new \app\admin\model\staff\Staff;
        $this->service_model = new \app\admin\model\service\Service;
        $this->order_goods_model = new \app\admin\model\order\Goods;
        $this->order_item_model = new \app\admin\model\wanlshop\OrderItem;
        $this->order_item_info_model = new \app\admin\model\order\ItemInfo;
        $this->order_model = new \app\admin\model\order\Order;
        $this->coupon_receive_model = new \app\admin\model\wanlshop\CouponReceive;
        $this->tag_model = new \app\admin\model\wanlshop\Tag;
        $this->tag_user_model = new \app\admin\model\wanlshop\TagUser;
        $this->cur_shop = Session::get('shop');
        $this->admin_shop = Session::get('adminshop');
        $this->grouplist = $this->user_group_model->order('id desc')->where('status','normal')->select();
        $groupdata = [];
        foreach ($this->grouplist as $k => $v) {
            $groupdata[$v->id] = ['id'=>$v->id,'name' => $v->name];
        }

        $this->view->assign("groupList", $groupdata);

        $condition = ['status'=>'normal'];

        //店铺列表
        $shopList = [];
        $_shopList = $this->shop_model->field('id,shopname')->where($condition)->select();
        foreach ($_shopList as $k => &$v) {
            $shopList[$v['id']] = $v['shopname'];
        }
        $this->view->assign('shopList', $shopList);
        
        //推荐人列表
        $juserList = [0 => __('None')];
        $_juserList = $this->model->field('id,nickname')->where($condition)->select();
        foreach ($_juserList as $k => &$v) {
            $juserList[$v['id']] = $v['nickname'];
        }
        $this->view->assign('juserList', $juserList);

        //营销顾问列表
        $serviceList = [0 => __('None')];
        $_serviceList = $this->service_model->field('id,name')->where($condition)->select();
        foreach ($_serviceList as $k => &$v) {
            $serviceList[$v['id']] = $v['name'];
        }
        $this->view->assign('serviceList', $serviceList);

        //营销顾问列表/员工列表
        $condition = ['status'=>'1'];
        $marketingList = [0 => __('None')];
        $_marketingList = $this->staff_model->field('id,name')->where($condition)->select();
        foreach ($_marketingList as $k => &$v) {
            $marketingList[$v['id']] = $v['name'];
        }
        $this->view->assign('marketingList', $marketingList);
        $this->view->assign('staffList', $marketingList);

        $wxmanageList = ['0'=>'无', '1'=>'门店', '2'=>'服务商'];
        $this->view->assign('wxmanageList', $wxmanageList);

        $group_id = Db::name('auth_group_access')->where('uid',$this->auth->id)->value('group_id');
        $isbcauth =0;
        //小程序权限编辑
        if($group_id==1){
            $isbcauth=1;
        }

        $this->view->assign('isbcauth',$isbcauth);
        $this->view->assign('shop_id',Session::get('shop'));
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {

            // 获取前端传递的筛选参数
            $_filter = $this->request->get('is_investor');
            $params = $this->request->get();
            // print_r($_filter);die;
            
            $condition = [];
            $condition['user.status'] = 'normal';
            if ($this->admin_shop != 1) {
                $condition['user.shop_id'] = $this->cur_shop;
            }
            if ($_filter == 1) {
                $condition['is_investor'] = '1';
                $this->model->where('is_investor', 1);
            }

            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            if (isset($params['filter']) && !empty($params['filter'])) {
                $filter = json_decode($params['filter'],true);
                if (isset($filter['tag_id'])) {
                    $user_ids = $this->tag_user_model->where('tag_id',$filter['tag_id'])->column('user_id');
                    $condition['user.id'] =['in',$user_ids];
                    unset($filter['tag_id']);
                }
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with('group,shop')
                ->where($where)
                ->where($condition)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $k => &$v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);
                //消费次数
                $v->ordercount = $this->order_model->where(['user_id'=>$v->id,'status'=>'normal','state'=>['in',[2,3,4,5,6]]])->count();
                //消费金额
                $v->orderfee = $this->order_model->where(['user_id'=>$v->id,'status'=>'normal','state'=>['in',[2,3,4,5,6]]])->sum('actual_price');

                $order_list = $this->order_model->field('createtime')->where(['user_id'=>$v->id,'status'=>'normal','state'=>['in',[2,3,4,5,6]]])->limit(1)->select();
                //上次消费时间
                $v->orderdate = '-';
                if (count($order_list)>0) {
                    $v->orderdate = date('Y-m-d',$order_list[0]['createtime']);
                }
                
                //持卡
                $count_item = $this->order_item_model->where(['user_id'=>$v->id,'status'=>'normal'])->count();
                $v->cardnumber = $count_item.'张';

                $tags = $this->tag_user_model->alias('tu')
                        ->join('wanlshop_tag t', 't.id=tu.tag_id', 'left')
                        ->where('tu.user_id',$v->id)
                        ->column('name');
                $v->tagsname = '';
                if (count($tags)>0) {
                    $v->tagsname = implode(',', $tags);
                }
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    // public function add()
    // {
    //     if ($this->request->isPost()) {
    //         $this->token();
    //     }
    //     return parent::add();
    // }
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $params['salt'] = Random::alnum();
            if ($params['password'] == '') {
                $params['password'] = '123456';
            }
            $params['password'] = md5(md5($params['password']) . $params['salt']);
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     */
    // public function edit($ids = null)
    // {
    //     if ($this->request->isPost()) {
    //         $this->token();
    //     }
    //     $row = $this->model->get($ids);
    //     $this->modelValidate = true;
    //     if (!$row) {
    //         $this->error(__('No Results were found'));
    //     }
    //     return parent::edit($ids);
    // }

    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            if ($row->salt == '') {
                $params['salt'] = Random::alnum();
                $params['password'] = md5(md5($params['password']) . $params['salt']);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        Auth::instance()->delete($row['id']);
        $this->success();
    }

    /**
     * 删除卡项
     */
    public function delitem($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->order_item_model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->order_item_model->where('id',$row['id'])->update(['status'=>'hidden']);
        $this->order_item_info_model->where('order_item_id',$row['id'])->update(['status'=>'hidden']);
        $this->success();
    }


    /**
     * 删除卡项
     */
    public function delserver($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->order_goods_model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->order_goods_model->where('id',$row['id'])->update(['valid'=>'0','validtime'=>time()]);
        $this->success();
    }

     /**
     * 详情
     */
    public function detail($ids = null){
        if ($this->request->isPost()) {
            $this->token();
        }

        $row = $this->model->get($ids);

        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $group_row = $this->user_group_model->where('status','normal')->find($row['group_id']);

        $row['createtime'] = date('Y-m-d H:i:s',$row['createtime']); 

        $juser_user = $this->model->where('id',$row['juser_id'])->value('nickname');

        //推荐人/客户来源
        $row['juser_user'] = empty($juser_user)?'暂无':$juser_user;

        //所属门店
        $shop_name = $this->shop_model->where('id',$row['shop_id'])->value('shopname');

        $row['shop_name'] = empty($shop_name)?'暂无':$shop_name;
        
        //用户标签
        $user_tags = $this->tag_user_model->where('user_id',$ids)->with('Tag')->select();

        $this->assign('userData',$row);


        $this->assign('userTags',$user_tags);

        $this->assign('groupName',$group_row?$group_row['name']:'');

        $this->assignconfig('user_id', $ids);

        //卡项
        $con = [];
        $con['user_id'] = $ids;
        // $con['status'] = 'normal';
        $order_item_list = $this->order_item_model->where($con)->order('status asc,createtime desc')->select();
        $order_item_count = count($order_item_list);
        if ($order_item_count > 0) {
            foreach ($order_item_list as &$value) {
                $value['is_available'] = 1;
                $value['item_type_unit']=config('item_type_unit')[$value['type']]??'';
                $_shop_name = $this->shop_model->where('id',$value['shop_id'])->value('shopname');
                $value['shop_name'] = empty($_shop_name)?'无':$_shop_name;
                if($value['validity'] == 9999){
                    $value['validitytime'] = '永久有效';
                }

                if ($value['validity'] == 1 && $value['validitytime'] < time()) {
                    $value['is_available'] = 0;
                }

                if ($value['status'] == 'hidden') {
                    $value['is_available'] = 0;
                }

                $value['bgcolor'] = '#e4c477';
                if($value['type'] == 4){
                    $value['bgcolor'] = '#626ea4';
                }
            }
        }

        $this->assignconfig('user_id', $ids);
        $this->view->assign("orderItemList", $order_item_list);
        $this->view->assign("orderItemCount", $order_item_count);

        //服务列表
        $where = [];
        $where['user_id'] = $ids;
        $where['state'] = 6;
        $order_ids = $this->order_model->where($where)->column('id');

        $con = [];
        $con['order_id'] = ['IN',$order_ids];
        $con['status'] = 'normal';
        $con['gdtype'] = '1';
        $con['is_gift'] = '1';

        $order_goods_list = $this->order_goods_model->where($con)->order('createtime desc')->select();
        if (count($order_goods_list) > 0) {
            foreach ($order_goods_list as $key => &$value) {
                $value['title'] .= '<span style="margin-left:5px;color: #f75444;border-radius: 10px;border: 1px solid red;font-size: 12px;padding: 3px;">赠</span>';
                if($value['valid'] == '1' && $value['validtime'] >= time()){
                    $value['bgcolor'] = '#e4c477';
                    $value['valid'] = '有效';
                    $value['is_valid'] = 1;
                    $value['validtime'] = date('Y-m-d H:i:s',$value['validtime']);
                }else{
                    $value['bgcolor'] = '#edf2fa';
                    $value['valid'] = '已失效';
                    $value['is_valid'] = 0;
                    $value['validtime'] = date('Y-m-d H:i:s',$value['validtime']);
                }
            }
        }

        $order_goods_count = count($order_goods_list);

        $this->view->assign("orderGoodsList", $order_goods_list);
        $this->view->assign("orderGoodsCount", $order_goods_count);

        //优惠券领取
        $where = ['user_id'=>$ids];
        $coupon_list = $this->coupon_receive_model->where($where)->order('createtime desc')->select();
        $coupon_count = count($coupon_list);
        if ($coupon_count > 0) {
            foreach ($coupon_list as &$_value) {
                $_shop_name = $this->shop_model->where('id',$_value['shop_id'])->value('shopname');
                $_value['shop_name'] = empty($_shop_name)?'无':$_shop_name;
            }
        }

        //充值卡余额
        $recharge_balance = 0;
        $where = ['status'=>'normal','type'=>4,'user_id'=>$ids];
        $recharge_list = $this->order_item_model->where($where)->select();
        if (count($recharge_list)>0) {
            foreach ($recharge_list as $rkey => $rvalue) {
                if ($rvalue['validitytime'] != 9999 && $rvalue['validitytime'] < time()) {
                    unset($recharge_list[$rkey]);
                }
                $recharge_balance += $rvalue['spent'];
                
            }
        }

        //统计信息
        $where = [];
        $where['user_id'] = $row['id'];
        $where['shop_id'] = $this->cur_shop;
        $where['state'] = ['in',[2,3,4,5,6]];
        $total_order_fee = $this->order_model->where($where)->count('actual_price');

        //总消费次数
        unset($where['state']);
        $total_order_times = $this->order_model->where($where)->count();

        //最近消费时间
        $total_order_time = $this->order_model->where($where)->order('createtime desc')->limit(1)->value('createtime');
        $total_order_time = empty($total_order_time)?'':date('Y-m-d',$total_order_time);

        //到店次数
        $where['ontype'] = 2;
        $offline_order_times = $this->order_model->where($where)->count();

        //上一次到店
        $last_order_time = $this->order_model->where($where)->order('createtime desc')->limit(1)->value('createtime');
        $last_order_time = empty($last_order_time)?'':date('Y-m-d',$last_order_time);

        $this->view->assign("total_order_fee", $total_order_fee);
        $this->view->assign("total_order_times", $total_order_times);
        $this->view->assign("total_order_time", $total_order_time);
        $this->view->assign("last_order_time", $last_order_time);
        $this->view->assign("offline_order_times", $offline_order_times);
        $this->view->assign("couponList", $coupon_list);
        $this->view->assign("recharge_balance", $recharge_balance);
        $this->view->assign("couponCount", $coupon_count);
        return $this->view->fetch();
    }

      /**
     * 导入
     *
     * @return void
     * @throws PDOException
     * @throws BindParamException
     */
    public function import(){
        // 开始事务
        Db::startTrans();
        try {
            $file = $this->request->request('file');
            if (!$file) {
                throw new Exception(__('Parameter %s can not be empty', 'file'));
            }
            
            $filePath = ROOT_PATH . DS . 'public' . DS . $file;
            if (!is_file($filePath)) {
                throw new Exception(__('No results were found'));
            }
            
            $ext = pathinfo($filePath, PATHINFO_EXTENSION);
            if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
                throw new Exception(__('Unknown data format'));
            }

            // 根据文件类型选择解析器
            if ($ext === 'csv') {
                $reader = new Csv();
            } elseif ($ext === 'xls') {
                $reader = new Xls();
            } else {
                $reader = new Xlsx();
            }

            // 加载文件
            $objPHPExcel = $reader->load($filePath);
            $sheet = $objPHPExcel->getSheet(0);
            $highestRow = $sheet->getHighestRow();
            $highestColumn = $sheet->getHighestColumn();

            // 读取表头
            $headers = [];
            $headers = ['id','nickname','mobile','gender','birthday','code','createtime','jointime','shop','juser','remark'];

            // 成功插入计数
            $successCount = 0;
            
            // 逐行处理数据
            for ($row = 2; $row <= $highestRow; $row++) {
                try {
                    $rowData = [];
                    for ($col = 1; $col < count($headers)+1; $col++) {
                        $cell = $sheet->getCellByColumnAndRow($col, $row);
                        $rowData[$headers[$col-1]] = trim($cell->getValue());
                    }

                    // 检查数据是否为空
                    if(empty($rowData['mobile'])) {
                        write_log_record('第'.$row.'行数据手机号为空，跳过处理');
                        continue;
                    }
                    
                    // 处理单条数据
                    $this->processSingleRow($rowData);
                    
                    $successCount++;
                    
                } catch (\Exception $e) {
                    // 记录单行错误但继续处理下一行
                    write_log_record('第'.$row.'行数据处理失败: '.$e->getMessage());
                    continue;
                }
            }

            if ($successCount == 0) {
                throw new Exception(__('No valid data was processed'));
            }
            
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            write_log_record('导入失败: ' . $e->getMessage());
            $this->error($e->getMessage());
        }

        $this->success(__('导入成功'), null, ['count' => $successCount]);
    }

    /**
     * 处理单行数据并插入数据库
     */
    protected function processSingleRow(&$row) {
        unset($row['id']);
        // 检查重复
        $exist = $this->model->where('username|mobile', $row['mobile'])->find();
        if($exist){
            throw new Exception('手机号('.$row['mobile'].')重复');
        }
        
        $row['username'] = $row['mobile'];
        $row['gender'] = $this->convertGender($row['gender']);
        $row['salt'] = Random::alnum();
        $row['password'] = $this->auth->getEncryptPassword('123456', $row['salt']);

        if ($row['birthday'] == '-' || empty($row['birthday'])) {
            $row['birthday'] = null;
        }

        $date = str_replace(".", "-", $row['createtime']); // 转为"2025-7-4"
        $row['createtime'] = strtotime($date);
         
        $row['jointime'] = ($row['jointime'] == '-' || empty($row['jointime']))? time():strtotime($row['jointime']);
        $shop_id = $this->shop_model->where('shopname',$row['shop'])->value('id');
        $row['shop_id'] = empty($shop_id)?0:$shop_id;
        $juser = $this->model->where('nickname',$row['juser'])->value('id');
        $row['juser_id'] = empty($juser)?0:$juser;
        unset($row['juser'], $row['shop']);
        // 单条插入
        $result = $this->model->insert($row);
        if (false === $result) {
            throw new Exception('数据插入失败');
        }
    }

    /**
     * 转换性别
     */
    protected function convertGender($gender) {
        if ($gender == '男') return 1;
        if ($gender == '女') return 0;
        return 2; // 默认未知
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function addusertag($ids = null)
    {   
        if (false === $this->request->isPost()) {
            //未分组标签
            $group_0 = [];
            //充值客户标签
            $group_1 = [];
            //客户等级标签
            $group_2 = [];
            //用户已选择标签列表
            $user_tags_list = [];
            
            //用户已选择标签
            $where = ['user_id'=>$ids];
            $user_tags = $this->tag_user_model->where($where)->column('tag_id');
            $tegs_count = count($user_tags);

            $where = ['status'=>'normal'];
            $all_tags = $this->tag_model->where($where)->field('id,name,group')->select();

            if (count($all_tags)>0) {
                foreach ($all_tags as $key => $value) {
                    if($value['group'] == 0){
                        $group_0[] = $value;
                    }elseif ($value['group'] == 1) {
                        $group_1[] = $value;
                    }elseif ($value['group'] == 2) {
                        $group_2[] = $value;
                    }

                    if($tegs_count > 0 && in_array($value->id, $user_tags)){
                        $user_tags_list[] = $value;
                    }
                }
            }

            $this->view->assign("group0", $group_0);
            $this->view->assign("group1", $group_1);
            $this->view->assign("group2", $group_2);
            $this->view->assign("usertags", $user_tags);
            $this->view->assign("usertagslist", $user_tags_list);
            $this->view->assign("tagscount", $tegs_count);
            $this->view->assign("user_id", $ids);

            return $this->view->fetch();
        }

        $params = $this->request->post('row/a');

        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }

        $user_id = $params['user_id'];

        $tag_ids = isset($params['tag_id'])?$params['tag_id']:[];

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->tag_user_model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->tag_user_model->validateFailException()->validate($validate);
            }
            $data = [];
            $del_data = [];
            $user_tags = $this->tag_user_model->where('user_id',$user_id)->column('tag_id');

            //取消的tag删除掉
            if (count($user_tags)>0) {
                foreach ($user_tags as $_key => $_value) {
                    if (!in_array($_value,$tag_ids)) {
                        $del_data[] = $_value;
                        $res = $this->tag_user_model->where(['user_id'=>$user_id,'tag_id'=>$_value])->delete();
                    }
                }
            }

            if(count($tag_ids) > 0){
                foreach ($tag_ids as $key => $value) {
                    $condition = ['user_id'=>$user_id,'tag_id'=>$value];
                    $info = $this->tag_user_model->where($condition)->find();
                    if (empty($info)) {
                        $data[] = $condition;
                    }
                }

                $result = $this->tag_user_model->allowField(true)->saveAll($data);
            }else{
                $result = true;
            }
            
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    public function addtag()
    {
        if (true === $this->request->isPost()) {
            $params = trim($this->request->post('tag_name'));

            if (empty($params)) {
                $this->error(__('Parameter %s can not be empty', ''));
            }

            $exist_tag = $this->tag_model->where('name',$params)->find();
            if ($exist_tag) {
                $this->error(__('当前标签已存在'));
            }

            $data = ['name'=>$params];
            $result = $this->tag_model->save($data);

            if ($result) {
                $this->success();
            }else{
                $this->error(__('保存失败'));
            }

        }


        $this->success();
    }

    public function addusercommontag()
    {
        if (true === $this->request->isPost()) {
            $user_id = $this->request->post('user_id');
            $tag_name = trim($this->request->post('tag_name'));

            if (empty($user_id) || empty($tag_name)) {
                $this->error(__('Parameter %s can not be empty', ''));
            }

            $exist_tag = $this->tag_model->where('name',$tag_name)->find();
            if ($exist_tag) {
                $this->error(__('当前标签已存在'));
            }

            Db::startTrans();
            try {
                $data = ['name'=>$tag_name];
                $res = $this->tag_model->save($data);
                $tag_id = $this->tag_model->getLastInsID();
                if ($res && $tag_id) {
                    $data = ['tag_id'=>$tag_id,'user_id'=>$user_id];
                    $result = $this->tag_user_model->save($data);
                }
                
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($res === false || $result === false) {
                $this->error(__('No rows were inserted'));
            }
            $this->success();
        }
        $this->success();
    }

}
